package com.lfk.blog.utils.quartz;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class StartListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private Scheduler scheduler;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        TriggerKey triggerKey=TriggerKey.triggerKey("trigger1","group1");
        try {
            Trigger trigger=scheduler.getTrigger(triggerKey);
            if(trigger==null){
                trigger= TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey)
//                        .withSchedule(CronScheduleBuilder.cronSchedule("0/59 * * * * ?"))
                        .withSchedule(CronScheduleBuilder.cronSchedule("0 0 9,21 * * ?"))
                        .build();
                JobDetail jobDetail=JobBuilder.newJob(ClearImgJob.class)
                        .withIdentity("job1","group1")
                        .build();
                scheduler.scheduleJob(jobDetail,trigger);
                scheduler.start();
            }
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }
}
